package com.webServer.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther:SYZ
 * @Date:2022/8/2 - 08 - 02 - 11:27
 * @Description:
 * @version:1.0
 */
public class ParseString {
    /***
     * 解析请求体
     * 通过socket获取的输入流读取客户端发送过来的一行字符串
     * @param line
     * @return
     * @throws IOException
     */
    public static String readLine(InputStream line) throws IOException {
        char pre='a',cur='a';
        StringBuilder builder = new StringBuilder();
        int d;
        while ((d=line.read()) != -1){
            cur = (char) d;
            //判断是否换行CRLF,换行则一行的数据读取完毕
            if(pre==13 && cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    /***
     * 解析uri参数路径,格式为:username=value&password=value
     * @param line
     * @return
     */
    public static Map<String,String> parseParameter(String line){
        HashMap<String, String> map = new HashMap<>();
        //解码转为UTF-8
        try {
            line = URLDecoder.decode(line,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //拆分成String数组
        String[] data = line.split("&");
        //遍历数组
        for (String datum : data) {
            //再拆分成String数组
            String[] paras = datum.split("=");
            //放入map中.  注意:'='右侧可能会没有参数,需要判断
            map.put(paras[0],paras.length>1?paras[1]:null);
        }
        return  map;
    }

    /***
     * 将一行字符串按照ISO8859-1编码发送给客户端,最后会自动添加回车和换行符
     * @param line
     * @param socket
     * @throws IOException
     */
    public static void send(String line, Socket socket) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        out.write(data);
        out.write(13);//单独发送了回车符
        out.write(10);//单独发送换行符
    }
}
